﻿app.factory('ItemsService', ['$http', '$q', 'AlertService', function ($http, $q, AlertService) {
    var items = [];
    var loadItemsDeferred = $q.defer();

    var loadTodoItems = function () {
        $http({
            //url: 'https://nickstodos.firebaseio.com/.json',
            url: 'http://localhost:18705/api/apiTodo',
            method: 'GET',
        }).success(function (data) {
            for (var n in data) {
                data[n].id = n;
                items.push(data[n]);
            }
            AlertService.addAlert('Todos loaded successfully');
            loadItemsDeferred.resolve(items);
        }).error(function () {
            AlertService.addAlert('Failed to load Todos');
            loadItemsDeferred.reject();
        });
    }

    loadTodoItems();

    var getTodoItems = function () {
        return loadItemsDeferred.promise;
    };

    var getTodoItem = function (id) {
        var deferred = $q.defer();
        var todo;
        for (var index in items) {
            if (items[index].id == id) {
                todo = items[index];
                break;
            }
        }

        if (todo) {
            deferred.resolve(todo);
        }
        else {
            $http({
                url: 'https://nickstodos.firebaseio.com/' + id + '/.json',
                method: 'GET'
            }).success(function (data) {
                data.id = id;
                items.push(data);
                deferred.resolve(data);
            });
        }

        return deferred.promise;
    }

    var addTodoItem = function (text, user, city) {
        var t = {
            text: text,
            dateCreated: new Date(),
            isCompleted: false,
            user: user,
            city: city
        };

        var deferred = $q.defer();
        $http({
            url: 'https://nickstodos.firebaseio.com/.json',
            method: 'POST',
            data: t
        }).success(function (data) {
            t.id = data;
            items.push(t);
            AlertService.addAlert('"' + t.text + '" added successfully');
            deferred.resolve(t);
        }).error(function () {
            AlertService.addAlert('Failed to add "' + t.text + '"');
            deferred.reject();
        });

        return deferred.promise;
    }

    return {
        addTodoItem: addTodoItem,
        getTodoItems: getTodoItems,
        getTodoItem: getTodoItem
    };
}]);